package com.dongwu.security.web;

import com.dongwu.common.dto.Result;
import com.dongwu.common.utils.Collections3;
import com.dongwu.common.utils.Exceptions;
import com.dongwu.common.utils.StringUtils;
import com.dongwu.common.web.BaseController;
import com.dongwu.common.web.Servlets;
import com.dongwu.manager.entity.TemplateType;
import com.dongwu.manager.service.TemplateTypeService;
import com.dongwu.security.entity.Group;
import com.dongwu.security.entity.Role;
import com.dongwu.security.entity.User;
import com.dongwu.security.service.IGroupService;
import com.dongwu.security.service.IRoleService;
import com.dongwu.security.service.IUserService;
import com.dongwu.security.service.impl.CustomUserDetailsService;
import com.dongwu.security.utils.SecurityUtils;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserCache;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.cache.NullUserCache;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Controller("sysUserController")
@RequestMapping("/security/user")
public class UserController extends BaseController<User, String> {

	@Autowired
	private IRoleService roleService;

	@Autowired
	private IGroupService groupService;

	@Value("${dongwu.security.user.queryRole}")
	private String queryRole;

	@Value("${dongwu.security.user.addRole}")
	private String addRole;

	@Value("${dongwu.security.user.editRole}")
	private String editRole;

	@Value("${dongwu.security.user.deleteRole}")
	private String deleteRole;

	@Value("${dongwu.security.user.batchDeleteRole}")
	private String batchDeleteRole;

	@Value("${dongwu.security.user.resetRole}")
	private String resetRole;

	public String getResetRole() {
		return resetRole;
	}

	@Autowired
	private IUserService userService;

	@Autowired
	private TemplateTypeService templateTypeService;

	@Autowired
	private CustomUserDetailsService customUserDetailsService;
	private UserCache userCache = new NullUserCache();
	public static final String RESET_PAGE = "{entityInstanceName}-reset";

	@RequestMapping(value = "/queryTree")
	@ResponseBody
	public Result queryTree(HttpServletRequest request) {

		try {
			List<Map<String, Object>> nodes = Lists.newArrayList();
			Map<String, Object> searchParams = Servlets
					.getParametersStartingWith(request, SEARCH_PARAM_PREFIX);
			System.out.println(searchParams);
			Iterable<User> users = userService.findList(searchParams);
			for (Iterator iter = users.iterator(); iter.hasNext();) {
				getUsersCascade((User) iter.next(), nodes);
			}
			return Result.successResult(nodes);

		} catch (Exception e) {
			String msg = Exceptions.getMessage(e);
			logger.error(msg, e);
			return Result.errorResult(msg);
		}

	}

	private void getUsersCascade(User user, List<Map<String, Object>> nodes) {

		Map<String, Object> userData = Maps.newHashMap();
		userData.put("tId", user.getId());
		userData.put("id", user.getId());
		userData.put("name", user.getName());

		nodes.add(userData);

	}

	@RequestMapping(value = "/add")
	public String add(ModelMap model) {

		List<Group> groups = groupService.findAll();
		List<TemplateType> templateTypes = templateTypeService.findAll();

		model.addAttribute("groups", groups);
		model.addAttribute("templateTypes", templateTypes);

		return super.add(model);

	}

	/*
	 * 编辑页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/edit/{id}")
	@Override
	public String edit(ModelMap model) {
		// List<Role> roles = roleService.findAll();
		// model.addAttribute("roles", roles);

		List<Group> groups = groupService.findAll();
		List<TemplateType> templateTypes = templateTypeService.findAll();

		model.addAttribute("groups", groups);
		model.addAttribute("templateTypes", templateTypes);

		return super.edit(model);
	}

	/*
	 * 编辑页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/reset/{id}")
	public String reset(ModelMap model) {

		if (!SecurityUtils.hasRole(this.getResetRole())) {
			return DENY_PAGE;
		}

		List<Role> roles = roleService.findAll();
		model.addAttribute("roles", roles);

		String page = getPagePath(RESET_PAGE);
		return page;
	}

	/**
	 * 修改
	 * 
	 * @param entity
	 * @return
	 */
	@RequestMapping(value = "/reset")
	@ResponseBody
	public Result reset(/* @RequestBody */@ModelAttribute("entity") User entity) {
		try {
			if (!SecurityUtils.hasRole(this.getResetRole())) {
				return Result.denyResult();
			}

			userService.save(entity);

			return Result.successResult();
		} catch (Exception e) {
			String msg = Exceptions.getMessage(e);
			logger.error(msg, e);
			return Result.errorResult(msg);
		}
	}

	public IRoleService getRoleService() {
		return roleService;
	}

	@Override
	public String getQueryRole() {
		return queryRole;
	}

	@Override
	public String getAddRole() {
		return addRole;
	}

	@Override
	public String getEditRole() {
		return editRole;
	}

	@Override
	public String getDeleteRole() {
		return deleteRole;
	}

	@Override
	public String getBatchDeleteRole() {
		return batchDeleteRole;
	}

	@RequestMapping(value = "/changepassword", method = RequestMethod.GET)
	public String getChangePasswordPage(HttpServletRequest request) {
		//return "changepassword";
		return "security/user/user-reset";
	}

	@RequestMapping(value = "/changePassword", method = RequestMethod.POST)
	@ResponseBody
	public String submitChangePasswordPage(
			@RequestParam("oldpassword") String oldPassword,
			@RequestParam("password") String newPassword,
			HttpServletRequest request) {
		System.out.println("change password.............");
		// SecurityContextHolder.clearContext();
		Authentication auth = SecurityContextHolder.getContext()
				.getAuthentication();
		String result = this.changePassword(auth.getName(), newPassword,
				oldPassword);

		request.getSession()
				.setAttribute(
						HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
						SecurityContextHolder.getContext());

		return result;
	}

	private String changePassword(String username, String newpassword,
			String oldpassword) {
		Authentication currentuser = SecurityContextHolder.getContext()
				.getAuthentication();

		if (currentuser == null) {

			// // This would indicate bad coding somewhere
			// throw new
			// AccessDeniedException("Can't change password as no Authentication object found in context "
			// +
			// "for current user.");
			return "请登录后再操作！";
		}

		Object principal = SecurityContextHolder.getContext()
				.getAuthentication().getPrincipal();

		User users = userService.findByLoginName(username);
		BCryptPasswordEncoder bpe = new BCryptPasswordEncoder();

		if (bpe.matches(oldpassword, users.getPassword())) {
			users.setPassword(newpassword);
			userService.save(users);

			SecurityContextHolder.getContext().setAuthentication(
					createNewAuthentication(currentuser, newpassword));

			userCache.removeUserFromCache(username);
			return "修改成功";

		}
		return "密码不正确";

	}

	public Authentication createNewAuthentication(Authentication currentAuth,
			String newPassword) {
		UserDetails user = customUserDetailsService
				.loadUserByUsername(currentAuth.getName());

		UsernamePasswordAuthenticationToken newAuthentication = new UsernamePasswordAuthenticationToken(
				user, user.getPassword(), user.getAuthorities());
		newAuthentication.setDetails(currentAuth.getDetails());

		return newAuthentication;
	}

	@ModelAttribute
	public void getEntity(
			@RequestParam(value = "id", defaultValue = "-1") String id,
			Model model) {
		if (!String.valueOf(id).equals("-1")) {
			User user = baseService.get(id);
			user.getRoles().clear();
			user.getUserGroups().clear();
			user.getDataPermission().clear();
			user.getUserTemplateTypes().clear();
			model.addAttribute("entity", user);
		}
	}

	protected void filterDataPermissionForce(Map<String, Object> searchParams) {
		String checkField = SecurityUtils
				.getDataPermissionCheckField(this.entityClass);

		String conditionKey = String.format("IN_%s", checkField);

		String valueStr = (String) searchParams.get(conditionKey);
		if (StringUtils.isNotEmpty(valueStr)) {
			List<String> values = Lists.newArrayList(valueStr.split(","));

			List<String> dataPermissions = SecurityUtils.getDataPermissions();
			if (!Collections3.isEmpty(dataPermissions)) {
				values.retainAll(dataPermissions);
			}
			searchParams.put(conditionKey, Joiner.on(",").join(values));
		} else {
			searchParams
					.put(conditionKey, SecurityUtils.getDataPermissionStr());
		}
	}

}
